package com.dhcc.sds.base.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.dhcc.cdc.busi.dao.CdcLocationMapper;
import com.dhcc.cdc.sys.dao.CdcProductMapper;
import com.dhcc.cdc.sys.dao.DictionaryMapper;
import com.dhcc.cdc.sys.dao.DictypeMapper;
import com.dhcc.cdc.sys.entity.CdcProductEntity;
import com.dhcc.cdc.sys.entity.DictionaryEntity;
import com.dhcc.cdc.sys.entity.DictypeEntity;
import com.dhcc.core.framework.security.ShiroKit;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.modules.system.dao.DeptUserMapper;
import com.dhcc.core.modules.system.entity.User;
import com.dhcc.sdc.base.dao.SdcBaseAssessmentMapper;
import com.dhcc.sdc.base.entity.SdcBaseAssessmentEntity;
import com.dhcc.sds.base.dao.*;
import com.dhcc.sds.base.entity.*;
import com.dhcc.sds.base.service.ISdsCommonService;
import com.dhcc.sds.base.service.ISdsIndexHeaderService;
import com.dhcc.sds.base.service.ISdsQcentityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @version 1.0 DHCC-SDS
 * @Description: 单病种公共服务接口实现类
 * @Project Name:
 * @Package Name:
 * @File Name:
 * @author:sunyingjie-医务管理
 * @date:2021年04月21日17:00:39
 * @Copyright: (c) DHCC All rights reserved.
 */
@Service("sdsCommonService")
public class SdsCommonServiceImpl implements ISdsCommonService {

    @Autowired
    private CdcProductMapper productMapper;
    @Autowired
    private DictypeMapper dictypeMapper;
    @Autowired
    private DictionaryMapper dictionaryMapper;
    @Autowired
    private SdsQcentityVersionMapper sdsQcentityVersionMapper;
    @Autowired
    private CdcLocationMapper cdcLocationMapper;
    @Autowired
    private SdsExpressMapper sdsExpressMapper;
    @Autowired
    private SdsCommonMapper sdsCommonMapper;
    @Autowired
    private DeptUserMapper deptUserMapper;
    @Autowired
    private SdsQcformItemMapper sdsQcformItemMapper;
    @Autowired
    private SdcBaseAssessmentMapper sdcBaseAssessmentMapper;
    @Autowired
    private SdsQcentityMapper sdsQcentityMapper;
    @Autowired
    private ISdsCommonService sdsCommonService;
    @Autowired
    private ISdsIndexHeaderService sdsIndexHeaderService;
    @Autowired
    private ISdsQcentityService sdsQcentityService;

    @Override
    public JSONObject getDicMap(String typeCode) {
        CdcProductEntity productEntity = new CdcProductEntity();
        productEntity.setCode("SDS");
        productEntity = productMapper.selectOne(productEntity);

        DictypeEntity dicType = new DictypeEntity();
        dicType.setProductId(productEntity.getId());
        dicType.setCode(typeCode);
        dicType = dictypeMapper.selectOne(dicType);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("dictypeId", dicType.getId());

        List<DictionaryEntity> dicList =  dictionaryMapper.list(map);

        JSONObject jsObj = new JSONObject();
        jsObj.put("","");
        for (DictionaryEntity dic : dicList) {
            jsObj.put(dic.getId().toString(), dic.getDescription());
        }
        return jsObj;
    }

    /**
     * 获取字典数组
     * @param typeCode
     * @return
     * [{id:xx,text:xx},{id:xx,text:xx}]
     */
    @Override
    public JSONArray getDicArray(String typeCode){
        JSONArray arr = new JSONArray();

        CdcProductEntity productEntity = new CdcProductEntity();
        productEntity.setCode("SDS");
        productEntity = productMapper.selectOne(productEntity);

        DictypeEntity dictypeEntity = new DictypeEntity();
        dictypeEntity.setProductId(productEntity.getId());
        dictypeEntity.setCode(typeCode);
        dictypeEntity = dictypeMapper.selectOne(dictypeEntity);
        if (!CommonUtil.isOneEmpty(dictypeEntity)) {
            Wrapper<DictionaryEntity> wrapper = new EntityWrapper<>();
            wrapper.eq("dictype_id", dictypeEntity.getId()).orderBy("id");
            List<DictionaryEntity> tipList = dictionaryMapper.selectList(wrapper);
            for (DictionaryEntity sde : tipList) {
                JSONObject obj = new JSONObject();
                obj.put("text", sde.getDescription());
                obj.put("id", sde.getId().toString());
                arr.add(obj);
            }
        }
        return arr;
    }

    @Override
    public JSONObject getVerMap() {
        JSONObject jsObj = new JSONObject();
        List<SdsQcentityVersionEntity> verList = sdsQcentityVersionMapper.list(new HashMap<>());
        jsObj.put("","");
        for (SdsQcentityVersionEntity ver : verList) {
            jsObj.put(ver.getId().toString(), ver.getVerDesc());
        }
        return jsObj;
    }

    @Override
    public JSONObject findDeptList(){
        JSONObject jsObj = new JSONObject();

        List<String> userDeptList = this.getDeptIdsBySysUser();
        Map map = new HashMap();
        map.put("userLinkDepts", userDeptList);
        List<Map<String, Object>> deptList = sdsCommonMapper.getDeptList(map);
        for (Map<String, Object> dept : deptList) {
            jsObj.put(dept.get("xcode").toString(), dept.get("name"));
        }

        return jsObj;
    }

    @Override
    public JSONObject findDeptList(String hospId){
        JSONObject jsObj = new JSONObject();

        List<String> userDeptList = this.getDeptIdsBySysUser();
        Map map = new HashMap();
        map.put("userLinkDepts", userDeptList);
        map.put("hospID", hospId);
        List<Map<String, Object>> deptList = sdsCommonMapper.getDeptList(map);
        for (Map<String, Object> dept : deptList) {
            jsObj.put(dept.get("xcode").toString(), dept.get("name"));
        }

        return jsObj;
    }



    @Override
    public JSONObject findHospList(){
        JSONObject jsObj = new JSONObject();

        String hospId = this.getHospIdBySysUser();
        Map map = new HashMap();
        map.put("userLinkHosp", hospId);
        List<Map<String, Object>> hospList = sdsCommonMapper.getHospList(map);
        for (Map<String, Object> hosp : hospList) {
            jsObj.put(hosp.get("id").toString(), hosp.get("name"));
        }

        return jsObj;
    }

    @Override
    public JSONArray getDepartMap(Map<String, Object> map) {
        List<String> userDeptList = this.getDeptIdsBySysUser();
        map.put("userLinkDepts", userDeptList);
        List<Map<String, Object>> deptList = sdsCommonMapper.getDeptList(map);
        JSONArray officeArry = new JSONArray();
        JSONObject obj = new JSONObject();
        obj.put("value", "");
        obj.put("text","全部");
        officeArry.add(obj);
        for (Map<String, Object> dept : deptList) {
            JSONObject officeObj = new JSONObject();
            officeObj.put("value", dept.get("xcode"));
            officeObj.put("text", dept.get("name"));
            officeArry.add(officeObj);
        }
        return officeArry;
    }

    @Override
    public JSONArray getMedicalGroupMap(Map<String, Object> map) {
        List<Map<String, Object>> groupList = sdsCommonMapper.getMedicalGroupList(map);
        JSONArray groupArry = new JSONArray();
        JSONObject obj = new JSONObject();
        obj.put("value", "");
        obj.put("text","全部");
        groupArry.add(obj);
        for (Map<String, Object> dept : groupList) {
            JSONObject groupObj = new JSONObject();
            groupObj.put("value", dept.get("xcode"));
            groupObj.put("text", dept.get("name"));
            groupArry.add(groupObj);
        }
        return groupArry;
    }

    /**
     * 通过字典类型CODE 获取函数字典
     * @param code
     * @return
     */
    @Override
    public JSONArray findExps(String code){
        JSONArray arr = new JSONArray();

        CdcProductEntity productEntity = new CdcProductEntity();
        productEntity.setCode("SDS");
        productEntity = productMapper.selectOne(productEntity);

        DictypeEntity dicType = new DictypeEntity();
        dicType.setProductId(productEntity.getId());
        dicType.setCode("SDExpType");
        dicType = dictypeMapper.selectOne(dicType);

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("dictypeId", dicType.getId());
        List<DictionaryEntity> dicList =  dictionaryMapper.list(map);
        for (DictionaryEntity dict : dicList) {
            if (code.equals(dict.getCode())) {
                map.clear();
                map.put("expType", dict.getId());
                break;
            }
        }

        List<SdsExpressEntity> TipExpList = sdsExpressMapper.list(map);
        for(SdsExpressEntity exp : TipExpList){
            JSONObject obj = new JSONObject();
            obj.put("text", exp.getExpDesc());
            obj.put("id", exp.getId().toString());
            arr.add(obj);
        }
        return arr;
    }

    /**
     * 通过字典类型CODE 函数代码 获取函数信息
     * @param dicCode
     * @return
     */
    @Override
    public SdsExpressEntity getExpEntity(String dicCode, String expCode){
        SdsExpressEntity expEntity = new SdsExpressEntity();

        CdcProductEntity productEntity = new CdcProductEntity();
        productEntity.setCode("SDS");
        productEntity = productMapper.selectOne(productEntity);

        DictypeEntity dicType = new DictypeEntity();
        dicType.setProductId(productEntity.getId());
        dicType.setCode("SDExpType");
        dicType = dictypeMapper.selectOne(dicType);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("dictypeId", dicType.getId());
        map.put("code", dicCode);
        DictionaryEntity dic = new DictionaryEntity();
        dic.setCode(dicCode);
        dic.setDictypeId(dicType.getId());
        dic =  dictionaryMapper.selectOne(dic);
        if (dic == null) {
            return expEntity;
        }
        SdsExpressEntity exp = new SdsExpressEntity();
        exp.setExpType(dic.getId().toString());
        exp.setExpCode(expCode);
        exp = sdsExpressMapper.selectOne(exp);
        return exp;
    }

    /**
     * 通过字典类型CODE 获取字典ID
     * @param typeCode
     * @param dictCode
     * @return
     */
    @Override
    public Long getDictId(String typeCode, String dictCode){
        if (CommonUtil.isEmpty(typeCode)||CommonUtil.isEmpty(dictCode)) {
            return null;
        }
        Long dictId = null;
        CdcProductEntity productEntity = new CdcProductEntity();
        productEntity.setCode("SDS");
        productEntity = productMapper.selectOne(productEntity);

        DictypeEntity dicType = new DictypeEntity();
        dicType.setProductId(productEntity.getId());
        dicType.setCode(typeCode);
        dicType = dictypeMapper.selectOne(dicType);

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("dictypeId", dicType.getId());
        List<DictionaryEntity> dicList =  dictionaryMapper.list(map);
        for (DictionaryEntity dict : dicList) {
            if (dictCode.equals(dict.getCode())) {
                dictId =  dict.getId();
                break;
            }
        }
        return dictId;
    }

    /**
     * 通过字典类型CODE 获取字典名称
     * @param typeCode
     * @param dictCode
     * @return
     */
    @Override
    public String getDictDesc(String typeCode, String dictCode){
        if (CommonUtil.isEmpty(typeCode)||CommonUtil.isEmpty(dictCode)) {
            return "";
        }
        String dictDesc = "";
        CdcProductEntity productEntity = new CdcProductEntity();
        productEntity.setCode("SDS");
        productEntity = productMapper.selectOne(productEntity);

        DictypeEntity dicType = new DictypeEntity();
        dicType.setProductId(productEntity.getId());
        dicType.setCode(typeCode);
        dicType = dictypeMapper.selectOne(dicType);

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("dictypeId", dicType.getId());
        List<DictionaryEntity> dicList =  dictionaryMapper.list(map);
        for (DictionaryEntity dict : dicList) {
            if (dictCode.equals(dict.getCode())) {
                dictDesc =  dict.getDescription();
                break;
            }
        }
        return dictDesc;
    }
    /**
     * 通过字典id 获取字典Code
     * @param dictId
     * @return
     */
    @Override
    public String getDictCode(Long dictId){
        if (dictId==null) {
            return "";
        }
        DictionaryEntity dict = dictionaryMapper.selectById(dictId);
        return dict.getCode();
    }

    /**
     * 获取当前登录用户关联的院区
     * @param
     * @return
     */
    @Override
    public String getHospIdBySysUser(){
        String hospId = "";
        // 获取当前登录用户的部门
        User user = ShiroKit.getUser();
        if (ObjectUtils.isEmpty(user)){
            return "";
        }
        long userid = user.getId();
        //验证是否为科主任角色
        if (ShiroKit.hasRole("DeptManager")) {
            hospId = sdsCommonMapper.getHospIdBySysUser(userid, "DeptManager");
        } else if (ShiroKit.hasRole("HospManager")) {
            //验证是否为医院/院区分管角色
            hospId = sdsCommonMapper.getHospIdBySysUser(userid, "HospManager");
        }

        return hospId;
    }

    /**
     * 获取当前登录用户关联的临床科室
     * @param
     * @return
     */
    @Override
    public List<String> getDeptIdsBySysUser(){
        List<String> deptList = new ArrayList<>();

        //验证是否为科主任角色
        if (ShiroKit.hasRole("DeptManager")) {
            // 获取当前登录用户的部门
            User user = ShiroKit.getUser();
            long userid = user.getId();
            deptList = sdsCommonMapper.getDeptsBySysUser(userid, "DeptManager");
        } else if (ShiroKit.hasRole("HospManager")) {
            // 获取当前登录用户的部门
            User user = ShiroKit.getUser();
            long userid = user.getId();
            //验证是否为医院/院区分管角色
            deptList = sdsCommonMapper.getDeptsBySysUser(userid, "HospManager");
        }

        return deptList;
    }

    @Override
    public JSONArray findFormItems(Long entityId) {
        JSONArray arr = new JSONArray();

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("entity_id", entityId);
        List<SdsQcformItemEntity> formItemList = this.sdsQcformItemMapper.list(map);
        for(SdsQcformItemEntity sdsQcformItemEntity : formItemList){
            JSONObject obj = new JSONObject();
            obj.put("text", sdsQcformItemEntity.getBtDesc());
            obj.put("id", sdsQcformItemEntity.getId().toString());
            arr.add(obj);
        }
        return arr;
    }

    @Override
    public JSONArray findFormItemTree(Long entityId) {
        JSONArray arr = new JSONArray();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("entity_id", entityId);
        List<SdsQcformItemEntity> sdsQcformItemEntities = this.sdsQcformItemMapper.selectItemCat(entityId);
        for (SdsQcformItemEntity sdsQcformItemEntity : sdsQcformItemEntities){
            JSONObject obj = new JSONObject();
            obj.put("text", sdsQcformItemEntity.getBtItemCat());
            obj.put("id", sdsQcformItemEntity.getId().toString());
            obj.put("state", "closed");
            List<SdsQcformItemEntity> itemEntities = this.sdsQcformItemMapper.selectItemByCat(entityId, sdsQcformItemEntity.getBtItemCat());
            JSONArray arrChildren = new JSONArray();
            for (SdsQcformItemEntity sdsQcformItemEntity1 : itemEntities){
                JSONObject objChildren = new JSONObject();
                objChildren.put("text", sdsQcformItemEntity1.getBtDesc() + "（" + sdsQcformItemEntity1.getBtTypeDict().getDescription() + "）");
                objChildren.put("id", sdsQcformItemEntity1.getId().toString());
                arrChildren.add(objChildren);
            }
            //基本信息增加死亡时间
//            JSONObject objChildren = new JSONObject();
//            objChildren.put("text", "死亡时间");
//            objChildren.put("id", "1001");
//            arrChildren.add(objChildren);
            obj.put("children", arrChildren);
            arr.add(obj);
        }
        //其他信息
        JSONObject otherObj = new JSONObject();
        otherObj.put("text", "其他信息");
        otherObj.put("id", "other");
        otherObj.put("state", "closed");
        JSONArray otherArrChildren = new JSONArray();
        
        JSONObject deathTime = new JSONObject();
        deathTime.put("text", "死亡时间");
        deathTime.put("id", "1001");
        otherArrChildren.add(deathTime);
        
        JSONObject isEvaluate = new JSONObject();
        isEvaluate.put("text", "是否已做VTE评估");
        isEvaluate.put("id", "1002");
        otherArrChildren.add(isEvaluate);
        
        otherObj.put("children", otherArrChildren);
        arr.add(otherObj);
        // 增加指标
        JSONObject obj = new JSONObject();
        obj.put("text", "单病种指标");
        obj.put("id", "singleDiseaseIndex");
        obj.put("state", "closed");
        SdsQcentityEntity sdsQcentityEntity = sdsQcentityService.selectById(entityId);
        JSONArray arrChildren = new JSONArray();
        JSONObject children = new JSONObject();
        children.put("text", sdsQcentityEntity.getBtDesc());
        children.put("id", sdsQcentityEntity.getId().toString());
        children.put("state", "closed");
        Map<String, Object> params = new HashMap<>();
        params.put("qcEntity", sdsQcentityEntity.getId());
        params.put("headerType", 2);
        params.put("indexType", 1);
        List<SdsIndexHeaderEntity> sonList = sdsIndexHeaderService.list(params);
        JSONArray arrChildren2 = new JSONArray();
        for (SdsIndexHeaderEntity sdsIndexHeaderEntity : sonList) {
            JSONObject diseaseIndex = new JSONObject();
            diseaseIndex.put("text", sdsIndexHeaderEntity.getTitle());
            diseaseIndex.put("id", sdsIndexHeaderEntity.getId().toString());
            arrChildren2.add(diseaseIndex);
        }
        children.put("children", arrChildren2);
        arrChildren.add(children);
        obj.put("children", arrChildren);
        arr.add(obj);
        return arr;
    }

    @Override
    public JSONObject getAsmtMap() {
        JSONObject obj = new JSONObject();
        Wrapper<SdcBaseAssessmentEntity> wpr = new EntityWrapper<>();
        wpr.eq("is_active", 1);
        List<SdcBaseAssessmentEntity> asmtList = sdcBaseAssessmentMapper.selectList(wpr);
        obj.put("","");
        for (SdcBaseAssessmentEntity asmt : asmtList) {
            obj.put(asmt.getId().toString(), asmt.getDescription());
        }
        return obj;
    }

    @Override
    public List<Map<String, String>> entityTestGroup() {
        return this.sdsCommonMapper.entityTestGroup();
    }

    @Override
    public JSONArray getDicCodeArray(String typeCode) {
        JSONArray arr = new JSONArray();

        CdcProductEntity productEntity = new CdcProductEntity();
        productEntity.setCode("SDS");
        productEntity = productMapper.selectOne(productEntity);

        DictypeEntity dictypeEntity = new DictypeEntity();
        dictypeEntity.setProductId(productEntity.getId());
        dictypeEntity.setCode(typeCode);
        dictypeEntity = dictypeMapper.selectOne(dictypeEntity);
        if (!CommonUtil.isOneEmpty(dictypeEntity)) {
            Wrapper<DictionaryEntity> wrapper = new EntityWrapper<>();
            wrapper.eq("dictype_id", dictypeEntity.getId()).orderBy("id");
            List<DictionaryEntity> tipList = dictionaryMapper.selectList(wrapper);
            for (DictionaryEntity sde : tipList) {
                JSONObject obj = new JSONObject();
                obj.put("text", sde.getDescription());
                obj.put("id", sde.getCode());
                arr.add(obj);
            }
        }
        return arr;
    }

    @Override
    public JSONArray getEntityMap() {
        Wrapper<SdsQcentityEntity> wpr = new EntityWrapper<>();
        wpr.eq("is_active", 1).orderBy("ind_no");
        List<SdsQcentityEntity> qcentityList = sdsQcentityMapper.selectList(wpr);
        JSONArray entityArry = new JSONArray();
        JSONObject obj = new JSONObject();
//        obj.put("value", "");
//        obj.put("text","全部");
//        entityArry.add(obj);
        for (SdsQcentityEntity entity : qcentityList) {
            JSONObject officeObj = new JSONObject();
            officeObj.put("value", String.valueOf(entity.getId()));
            officeObj.put("text", entity.getBtDesc());
            entityArry.add(officeObj);
        }
        return entityArry;
    }

    @Override
    public JSONArray getEntityMap(String entityType) {
        Long entityTypeId = sdsCommonService.getDictId("QcentityType",entityType);
        Wrapper<SdsQcentityEntity> wpr = new EntityWrapper<>();
        wpr.eq("entity_type_id",entityTypeId).eq("is_active", 1).orderBy("ind_no");
        List<SdsQcentityEntity> qcentityList = sdsQcentityMapper.selectList(wpr);
        JSONArray entityArry = new JSONArray();
        JSONObject obj = new JSONObject();
//        obj.put("value", "");
//        obj.put("text","全部");
//        entityArry.add(obj);
        for (SdsQcentityEntity entity : qcentityList) {
            JSONObject officeObj = new JSONObject();
            officeObj.put("value", String.valueOf(entity.getId()));
            officeObj.put("text", entity.getBtDesc());
            entityArry.add(officeObj);
        }
        return entityArry;
    }

    @Override
    public JSONArray getDepartGroupMap(Map<String, Object> map) {
        List<Map<String, Object>> deptGroupList = sdsCommonMapper.getDeptGroupList(map);
        JSONArray officeArry = new JSONArray();
        JSONObject obj = new JSONObject();
        obj.put("value", "");
        obj.put("text","全部");
        officeArry.add(obj);
        for (Map<String, Object> dept : deptGroupList) {
            JSONObject officeObj = new JSONObject();
            officeObj.put("value", dept.get("groupId"));
            officeObj.put("text", dept.get("groupName"));
            officeArry.add(officeObj);
        }
        return officeArry;
    }

    public static void main(String[] args) {
        String str = "1 2*\'c-b\"";
        char[] replaceArr = new char[]{(char)9,(char)10,(char)13,(char)32,(char)34,(char)39,(char)45,(char)47,(char)92};
        int l = replaceArr.length;
        for (int i = 0; i < l; i++) {
            str = str.replace(replaceArr[i], ' ');
        }
        Pattern p = Pattern.compile("\\s*");
        Matcher m = p.matcher(str);
        str = m.replaceAll("");
        System.out.println(str);
    }
}
